package com.dfbz.springboot_project.service.impl;

import com.dfbz.springboot_project.entity.Role;
import com.dfbz.springboot_project.mapper.RoleMapper;
import com.dfbz.springboot_project.service.RolePrivilegeService;
import com.dfbz.springboot_project.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    RolePrivilegeService rolePrivilegeService;
    @Override
    public PageInfo<Role> selectPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Role> roles = roleMapper.selectAll();
        for (Role role : roles) {
            List<String> privileges = roleMapper.selectPriByRid(role.getRoleId());
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < privileges.size(); i++) {
                sb.append(privileges.get(i)+"、");
            }
            if (sb.length()>0){
                sb.deleteCharAt(sb.length()-1);
            }
            role.setPrivileges(sb.toString());
        }
        return new PageInfo<>(roles);
    }
    @Override
    public List<Role> selectAll(){
        return roleMapper.selectAll();
    }
    @Override
    public List<Role> selectRoleNamesByAid(Integer Aid){
        return roleMapper.selectRolesByAid(Aid);
    }

    @Override
    public Role selectOne(Integer Rid) {
        Role role = new Role();
        role.setRoleId(Rid);
        return roleMapper.selectOne(role);
    }
    @Override
    public void update(Map<String, Object> params){
        Role role = new Role();
        role.setRoleId((Integer) params.get("Rid"));
        role.setRoleName((String) params.get("name"));
        roleMapper.updateByPrimaryKeySelective(role);
    }
    @Override
    public void deleteById(Integer Rid){
        roleMapper.deleteById(Rid);
    }
    @Override
    public void insert(Map<String, Object> params){
        Role role = new Role();
        role.setRoleName((String) params.get("name"));
        roleMapper.insertSelective(role);
    }
    @Override
    public void InsertSelective(Map<String, Object> params){
        Role role = new Role();
        role.setRoleName((String) params.get("name"));
        roleMapper.insertSelective(role);
        List<Role> roles = roleMapper.selectAll();
        Role role2 = roles.get(roles.size() - 1);
        Integer roleId = role2.getRoleId();
        params.put("Rid",roleId);
        rolePrivilegeService.insert(params);
    }
}
